import 'dart:convert';

import 'package:flutter/services.dart';
import 'package:flutterdev/constant/ApiConstant.dart';
import 'package:flutterdev/model/HomeModel.dart';
import 'package:http/http.dart' as http;

/// 接口请求服务
class ApiService {
  /// 请求首页接口数据，从网络加载数据进行解析
  static Future<HomeModel> requestHomeData() async {
    final response = await http.get(Uri.parse(ApiConstant.HOME_URL));
    if (response.statusCode == 200) {
      Utf8Decoder decode = Utf8Decoder();
      var result = json.decode(decode.convert(response.bodyBytes));
      return HomeModel.fromJson(result);
    } else {
      throw Exception('数据加载失败');
    }
  }

  /// 本地mock数据，直接读取JSON文件进行数据解析
  static Future<HomeModel> loadHomeData() async {
    final response = await rootBundle.loadString('assets/home_data.json');
    if (response.isNotEmpty) {
      var result = json.decode(response);
      return HomeModel.fromJson(result);
    } else {
      throw Exception('数据加载失败');
    }
  }
}
